package com.yanyilu.basing.controller;

import com.yanyilu.basing.common.R;
import com.yanyilu.basing.common.ResultCode;
import com.yanyilu.basing.jwt.JwtIgnore;
import com.yanyilu.basing.service.IUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("upload")
public class UploadController {

    @Autowired
    IUploadService uploadService;

    @Value("${uploadDir}")
    private String uploadDir;

    /**
     * 编辑器的文件上传*/
    @JwtIgnore
    @PostMapping("/admin/image")
    public R uploadEdit(@RequestParam(value = "file") MultipartFile file) throws RuntimeException {
        if (file.isEmpty()) {
            return R.ok().put("message", "文件为空");
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String filePath = uploadDir;
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String tempFileName = uuid + suffixName;
        String path = filePath +"temp"+suffixName;
        File dest = new File(path);
        String pth = "";
        try {
            file.transferTo(dest);
            pth = uploadService.toOSS(tempFileName, path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> data = new HashMap<>();
        data.put("src",pth);
        return R.ok().put("message", "图片上传成功").put("data",data);
    }

    @JwtIgnore
    @PostMapping("/file/image")
    public R uploadImageBase64(@RequestBody String base64Data) throws RuntimeException {
        String dataPrix = ""; //base64格式前头
        String data = "";//实体部分数据
        if (base64Data == null || "".equals(base64Data)) {
            return R.ok().put("message", "文件为空");
        } else {
            String[] d = base64Data.split("base64,");//将字符串分成数组
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                return R.ok().put("message", "上传失败，数据不合法");
            }
        }
        String suffix = "";//图片后缀，用以识别哪种格式数据
        //编码的jpeg图片数据
        if ("data:image/jpg;".equalsIgnoreCase(dataPrix)) {
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
            //编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
            //编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
            //编码的png图片数据
            suffix = ".png";
        } else if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
            //编码的png图片数据
            suffix = ".jpeg";
        } else if ("data:image/bmp;".equalsIgnoreCase(dataPrix)) {
            //编码的png图片数据
            suffix = ".bmp";
        } else if ("data:image/svg;".equalsIgnoreCase(dataPrix)) {
            //编码的png图片数据
            suffix = ".svg";
        } else if ("data:image/gfif;".equalsIgnoreCase(dataPrix)) {
            //编码的png图片数据
            suffix = ".gfif";
        } else {
            return R.ok().put("message", "上传失败，图片格式不正确");
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String tempFileName = uuid + suffix;
        String imgFilePath = uploadDir+tempFileName;//新生成的图片
        BASE64Decoder decoder = new BASE64Decoder();
        String pth="";
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(data);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    //调整异常数据
                    b[i] += 256;
                }
            }
            //保存图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            //imageService.save(imgurl);
            pth = uploadService.toOSS(tempFileName, uploadDir);
            return R.ok().put("message", "图片上传成功").put("downUrl", pth);
        } catch (IOException e) {
            return R.error(ResultCode.IMAGE_UPLOAD_fAIL);
        }
    }
}
